﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Collections;

namespace Blog.Core
{
    public abstract class BaseObject : IEditableObject
    {
        protected int _ID;

        protected BaseObject()
        { 
        }

        internal IList Parent
        {
            get;
            set;
        }

        [Browsable(false), ReadOnly(true)]
        public bool IsAdd
        {
            get { return _ID <= 0; }
        }

        [Browsable(false), ReadOnly(true)]
        public bool IsModify
        {
            get
            {
                return IsChanged || IsAdd || IsDelete;
            }
        }

        [Browsable(false), ReadOnly(true)]
        public bool IsDelete
        {
            get;
            private set;
        }

        [Browsable(false), ReadOnly(true)]
        public bool IsChanged
        {
            get;
            protected set;
        }

        [Browsable(false), ReadOnly(true)]
        public int ID
        {
            get
            {
                return _ID;
            }
        }

        protected virtual void OnPropertyChanged()
        {
            IsChanged = true;
        }

        public void SetDeleted()
        {
            IsDelete = true;
        }

        public void BeginEdit()
        {
        }

        public void CancelEdit()
        {
            if (IsAdd)
            {
                if (Parent != null && Parent.Contains(this))
                    Parent.Remove(this);

                Parent = null;
            }
        }

        public void EndEdit()
        {
            Save();
        }

        public virtual void Save()
        {
            if (!IsModify)
                return;

            if (IsDelete)
            {
                if (!IsAdd)
                    DeleteExecute();
            }
            else
            {
                SaveExecute();
                IsChanged = IsAdd;
            }
        }

        protected abstract void DeleteExecute();
        protected abstract void SaveExecute();
    }
}
